<?php
namespace app\admin\controller;

use my\Tools;
use think\Cache;
use think\Controller;
use think\Db;
use think\Session;

class Base extends Controller {
    public $base_condition = array();
    protected $mapData = [];
    /**
     * 析构函数
     */
    function __construct()
    {
        Session::start();
        header("Cache-control: private");
        parent::__construct();
    }

    /*
     * 初始化操作
     */
    public function _initialize()
    {
        defined('IS_POST') or define('IS_POST', $this->request->isPost());
        defined('IS_AJAX') or define('IS_AJAX', $this->request->isAjax());
        defined('IS_GET') or define('IS_GET', $this->request->isGet());
        //过滤不需要登录的行为
        if(!in_array(ACTION_NAME,array('login','jy','vjy','logout','vertify','auto_order','reset_now_in_arean'))){
            if(session('admin_id') > 0 ){
                //判断不是超管
                if(session('act_list') != 'all' && session('admin_type')>1){
                    $this->base_condition   = $this->baseCondition(session('admin_id'));
                }
                $this->check_priv();//检查管理员菜单操作权限
                //时时获取 - 权限及时生效
                //$act_list = session('act_list');
                $act_list = Db::name('admin')->join('xm_admin_role', 'xm_admin.role_id=xm_admin_role.role_id', 'INNER')->where(['admin_id'=>session('admin_id')])->value('act_list');
                $menu_list = getMenuList($act_list);
                //print_r($menu_list);die;
                $admin_info = Db::name('admin')->where("admin_id", session('admin_id'))->find();
                if($admin_info['is_init'] == 1 && strtolower(ACTION_NAME) != 'modify_pwd'){
                    exit("<script>alert('请先修改初始密码，再进行后续操作');parent.window.location.href = '/admin/admin/modify_pwd';</script>") ;
                }
                if($admin_info['is_css']==1){
                    $their_info = Db::name('their')->where("admin_id", session('admin_id'))->find();
                    $this->mapData['a.their_id']=$their_info['their_id'];
                    $this->assign('theirId',$their_info['their_id']);
                }
                $this->assign('admin_info',$admin_info);
                $key_arr = array_keys($menu_list);
                $firstkey_v = $key_arr[0];
                $this->assign('firstkey_v',$firstkey_v);
                $this->assign('menu_list',$menu_list);
            }else{
                $this->redirect(U('admin/Admin/login'));
            }
        }
    }

    /**
     * 保存公告变量到 smarty中 比如 导航
     */
    public function public_assign()
    {
        $config = array();
        $config = Db::name('config')->cache(true)->select();
        foreach($config as $k => $v)
        {
            $config[$v['inc_type'].'_'.$v['name']] = $v['value'];
        }
        $this->assign('config', $config);
    }

    public function check_priv()
    {
        $ctl = CONTROLLER_NAME;
        $act = ACTION_NAME;
        $a_handle = $ctl.'@'.$act;

        $param = $this->request->param();
        //$act_list = session('act_list');//session获取当前登录人的权限ID（字符串）
        //时时获取 - 权限及时生效
        $act_list = Db::name('admin')->join('xm_admin_role', 'xm_admin.role_id=xm_admin_role.role_id', 'INNER')->where(['admin_id'=>session('admin_id')])->value('act_list');

        //无需验证的操作
        $uneed_check = array('login','logout','vertifyHandle','vertify','getregion','upload','login_task','test');
        if($ctl == 'Index' || strtolower($ctl) == 'platform' || $act_list == 'all'){
            //do something
        }elseif(in_array($act,$uneed_check)){
            //do something
        }else{
            //$role_right = Cache::get('role_right_'.session('admin_id'));                                              //缓存读取菜单权限代码 - 不从缓存读
            //if(empty($role_right)){
            $right = Db::name('system_menu')->where("id", "in", $act_list)->column('right');
            $role_right = '';
            foreach ($right as $val){
                $role_right .= $val.',';
            }
            $role_right = explode(',', rtrim($role_right,','));
            //Cache::set('role_right_'.session('admin_id'),$role_right);
            //}
            //检查是否拥有此操作权限

            if(!in_array(strtolower($a_handle),array_map('strtolower',$role_right))){                         //判断当前访问的控制方法是否在勾选的权限内
                $msg = '您没有操作权限['.($a_handle).'],请联系超级管理员分配权限';
                if(request()->isAjax()){
                    respose(array('status'=>5,'msg'=>$msg));                                                            //对于ajax提交的控制器
                }
                $str = "<script type='application/javascript'>alert('$msg');</script>";
                //$str = "<script type='application/javascript'>alert('$msg');parent.window.location.reload();</script>";
                //if($_SERVER['HTTP_REFERER']){
                //$lasturl_arr = array_splice(explode('/', $_SERVER['HTTP_REFERER']), -3);
                //if(strtolower($lasturl_arr[0]) == 'admin'){
                exit($str);
                //}else{
                //    exit($str);
                //}
                //}else{
                //$this->error($msg,U('Admin/index/index'));exit;
                //}
            }
        }
        //记录操作日志(内网不记录)
        $this->handleAdmin($ctl,$a_handle,$param);
    }

    public function ajaxReturn($data,$type = 'json'){
        exit(json_encode($data));
    }

    public function httpsRequest($url, $data = null) {
        $curl = curl_init ();
        curl_setopt ( $curl, CURLOPT_URL, $url );
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
        if (! empty ( $data )) {
            curl_setopt ( $curl, CURLOPT_POST, 1 );
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
        }
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
        $output = curl_exec ( $curl );
        curl_close ( $curl );
        return $output;
    }

    //普通管理员基本限制条件
    protected function baseCondition($admin_id)
    {
        //$data = Cache::get('base_condition_'.$admin_id);
        $data = [];
        if(empty($data)){
            $where['admin_id'] = $admin_id;
            $region = db('region');
            $admin_area = db('admin_area');
            $admin_info = Db::name('admin')->where($where)->field('admin_type,region')->find();
            $region_area = $admin_area->where($where)->column('region_area');
            switch ($admin_info['admin_type']){
                case 2://省代理
                    //获取省下面所有 市/区域
                    $subQuery = $region->where('parent_id','in',$region_area)->field('region_id as city_id')->buildSql();
                    $info = $region->alias('co')->join("$subQuery ci",'co.parent_id = ci.city_id')->field('co.region_id as county_id,ci.city_id,co.region_code')->select();
                    foreach ($info as $key => $value){
                        $city_id[$key] = $value['city_id'];             //城市ID
                        $region_code[$key] = $value['region_code'];     //地区编码
                        $county_id[$key] = $value['county_id'];         //地区区域/县ID
                    }
                    $county_id      = array_unique($county_id);
                    $region_code    = array_unique($region_code);
                    $city_id        = array_unique($city_id);
                    $map['region_area'] = array(array('in',$region_area),array('in',$city_id),array('in',$county_id),'or');
                    break;
                case 3://市代理
                    $info = $region->where('parent_id','in',$region_area)->column('region_id as county_id,region_code');
                    foreach ($info as $key => $value){
                        $county_id[]    = $key;                 //地区区域/县ID
                        $region_code[]  = $value;               //地区编码
                    }
                    $map['region_area'] = array(array('in',$region_area),array('in',$county_id),'or');
                    break;
                case 4://市/区代理
                    $region_code = $region->where('region_id','in',$region_area)->column('region_code');//???
                    $map['region_area'] = array('in',$region_area);
                    break;
            }
            //查询目前后台有哪些操作用户
            $admin_ids = $admin_area->where($map)->group('admin_id')->column('admin_id');
            //echo $admin_area->getLastSql();
            $data = array('admin_type'=>$admin_info['admin_type'],'region'=>json_decode($admin_info['region'],true),
                'region_area'=>array('in',$region_area),'region_code'=>array('in',$region_code),'admin_id'=>array('in',$admin_ids));
            //print_r($data);
            //Cache::set('base_condition_'.$admin_id,$data);
        }
        return $data;
    }

    private function handleAdmin($ctl,$a_handle,$param)
    {
        if($a_handle != 'Index@index' && $a_handle != 'Index@main'){
            if($param && strpos(strtolower($ctl),'log')===false){
                if(in_array('page', array_keys($param))){
                    if($param['page']==1){
                        $this->adminLog($a_handle,$param);
                    }
                }else{
                    $this->adminLog($a_handle,$param);
                }
            }
        }
    }

    protected function adminLog($a_handle,$param='',$content='')
    {
        if(strpos(Tools::getIp(),'192.168.')===false && strpos(Tools::getIp(),'127.0.0.')===false) {
            $a_log['controls'] = $a_handle;
            $a_log['admin_name'] = session('admin_name');
            $time = Db::name('admin_log')->where($a_log)->order('log_id', 'desc')->value('add_time');
            if ((time() - $time) > 10) {
                $system_menu_arr = Db::name('system_menu')->where("find_in_set('{$a_log['controls']}',`right`)")->find();
                $a_log['content'] = $system_menu_arr ? $system_menu_arr['name'] : $content;
                $a_log['add_time'] = time();
                $a_log['admin_id'] = session('admin_id');
                $a_log['IP'] = Tools::getIp();
                $param && $a_log['param'] = json_encode($param);
                Db::name('admin_log')->insertGetId($a_log);
            }
        }
    }

    /**
     * 将管理员管理的区域存入redis
     * @param $admin_id
     * @return  mixed
     * */
    protected function cacheAdminArea($admin_id)
    {
        $admin_info = Db::name('admin')->where("admin_id", $admin_id)->field('admin_type,region')->find();
        $region = json_decode($admin_info['region'],true);
        if($admin_info['admin_type']<2){
            return false;
        }
        $region_db = db('region p');
        $region_id_city = $region_id_county = array();
        foreach ($region[3] as $val){
            $region_id_city = array_merge($region_id_city,$val);
        }
        foreach ($region[4] as $value){
            $region_id_county = array_merge($region_id_county,$value);
        }
        $map['p.region_id'] = array('in',$region[2]);
        switch ($admin_info['admin_type']){
            //省级
            case 2:
                $admin_area = $region_db->where($map)->field('p.region_name as province')->select();
                break;
            case 3:
                $map['c.region_id'] = array('in',$region_id_city);
                $admin_area = $region_db->join('region c','p.region_id=c.parent_id')
                    ->where($map)->field('p.region_name as province,c.region_name as city')->select();
                break;
            case 4:
                $map['c.region_id'] = array('in',$region_id_city);
                $map['co.region_id'] = array('in',$region_id_county);
                $admin_area = $region_db->join('region c','p.region_id=c.parent_id')
                    ->join('region co','c.region_id=co.parent_id')->where($map)
                    ->field('p.region_name as province,c.region_name as city,co.region_name as county')->select();
                break;
        }
        $cache = array();
        foreach ($admin_area as $key => $val ){
            $cache[$key]['id'] = $key + 1;
            $cache[$key]['name'] = $val['province'].$val['city'].$val['county'];
        }
        //Cache::set("area_$admin_id",$cache);
        return $cache;
    }

    //区域统计
    protected function regionSta($admin_id)
    {
        $data = Cache::get('sta_condition_'.$admin_id);
        if(empty($data)){
            $base_condition = $this->base_condition;
            $map['co.region_name'] = array(array('eq',"市辖区"),array('like',"%县%"),array('like',"%市"),array('like',"%旗%"),'or');
            $field = 'p.region_name as province,p.region_id as province_id,c.region_name as city,c.region_id as city_id,
            co.region_name as county,co.region_id as county_id,co.region_code';
            if($base_condition){
                switch ($base_condition['admin_type']){
                    //省级
                    case 2:
                        $map['p.region_id'] = $base_condition['region_area'];
                        break;
                    case 3:
                        $map['c.region_id'] = $base_condition['region_area'];
                        break;
                    case 4:
                        $map['co.region_id'] = $base_condition['region_area'];
                        break;
                }
            }else{
                $map['p.parent_id'] = 1;
            }
            $db = db('region');$where['region_name'] = array('like',"%区");
            $region = Db::name('region p')->join('region c','c.parent_id=p.region_id','LEFT')
                ->join('region co','co.parent_id=c.region_id','LEFT')->where($map)->field($field)->order('p.region_id asc,co.region_code asc')->select();
            foreach ($region as $key => $val){
                $data[$val['province_id']]['name'] = $val['province'];
                $data[$val['province_id']][$val['city_id']]['name'] = $val['city'];
                $data[$val['province_id']][$val['city_id']][$val['county_id']]['name'] = $val['county'];
                $data[$val['province_id']][$val['city_id']][$val['county_id']]['region_code'] = array('in',$val['region_code']);
                $data[$val['province_id']][$val['city_id']][$val['county_id']]['county_id'] = array('in',$val['county_id']);
                if($val['county']=='市辖区'){
                    $where['parent_id'] = $val['city_id'];
                    $region_info = $db->where($where)->column('region_id,region_code');
                    $data[$val['province_id']][$val['city_id']][$val['county_id']]['county_id'] = array('in',array_keys($region_info));
                    $data[$val['province_id']][$val['city_id']][$val['county_id']]['region_code'] = array('in',array_values($region_info));
                }
            }
            Cache::set('sta_condition_'.$admin_id,$data);
        }
        return $data;
    }

    protected function clear_admin_cache($admin_id)
    {
        $admin_cache = config('admin_cache');
        foreach ($admin_cache as $val){
            Cache::rm($val.$admin_id);
        }
    }
}
